package com.zwl.module_db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.zwl.module_db.dao.BillDao
import com.zwl.module_db.entity.BillBean

@Database(
    entities = [BillBean::class],
    version = 2
)
//为什么是抽象类？ 因为我们只是定义信息，实例化是由ROOM来实现的。
abstract class InitDatabase: RoomDatabase() {

    abstract fun getBillDao(): BillDao

    companion object {
        @Volatile
        private var INSTANCE: InitDatabase? = null//数据库对象不推荐一直创建的，消耗资源，所以我们需要做成单例的。

        fun getDatabase(context: Context): InitDatabase {
            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }
            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    InitDatabase::class.java,
                    "init_database"
                ).addMigrations(MIGRATION_1_2)
                    .build()
                INSTANCE = instance
                return instance
            }
        }
        val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE bill ADD COLUMN age INTEGER NOT NULL DEFAULT 0")
            }
        }
    }



}

/*
假如说，你要新增一个字段，那么如下这样：
（1）新增age字段
@Entity(tableName = "bill")
data class BillBean(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,
    @ColumnInfo
    val time: Long,
    @ColumnInfo
    val thingError: String,
    @ColumnInfo
    val remark: String,
    @ColumnInfo(name = "age")
    val age: Int = 0 // 添加的新字段
)
（2）修改版本号
@Database(
    entities = [BillBean::class], // 注意这里使用的是实体类，不是Dao
    version = 2 // 增加版本号
)
abstract class InitDatabase: RoomDatabase() {
    // ...
}
(3)新增语句
val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("ALTER TABLE bill ADD COLUMN age INTEGER NOT NULL DEFAULT 0")
    }
}

（4）添加迁移
synchronized(this) {
    val instance = Room.databaseBuilder(
        context.applicationContext,
        InitDatabase::class.java,
        "init_database"
    ).addMigrations(MIGRATION_1_2) // 添加迁移
    .build()
    INSTANCE = instance
    return instance
}


如果后续还有则
val MIGRATION_2_3 = object : Migration(2, 3) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("ALTER TABLE bill ADD COLUMN address TEXT NOT NULL DEFAULT ''")
    }
}
synchronized(this) {
    val instance = Room.databaseBuilder(
        context.applicationContext,
        InitDatabase::class.java,
        "init_database"
    ).addMigrations(MIGRATION_1_2, MIGRATION_2_3) // 添加所有迁移
    .build()
    INSTANCE = instance
    return instance
}








 */